import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store'
import { ElMessage } from 'element-plus'

// 导入页面组件
import Layout from '@/layout/index.vue'
import Login from '@/views/login/index.vue'
import Dashboard from '@/views/dashboard/index.vue'
import NotFound from '@/views/error/404.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '首页', icon: 'House', affix: true }
      }
    ]
  },
  {
    path: '/vertical-projects',
    component: Layout,
    redirect: '/vertical-projects/list',
    name: 'VerticalProjects',
    meta: { title: '纵向课题', icon: 'Document' },
    children: [
      {
        path: 'list',
        name: 'VerticalProjectList',
        component: () => import('@/views/vertical-projects/list.vue'),
        meta: { title: '课题列表', icon: 'List' }
      },
      {
        path: 'create',
        name: 'VerticalProjectCreate',
        component: () => import('@/views/vertical-projects/form.vue'),
        meta: { title: '添加课题', icon: 'Plus', roles: ['STUDENT'] }
      },
      {
        path: 'edit/:id',
        name: 'VerticalProjectEdit',
        component: () => import('@/views/vertical-projects/form.vue'),
        meta: { title: '编辑课题', hidden: true, roles: ['STUDENT'] }
      }
    ]
  },
  {
    path: '/horizontal-projects',
    component: Layout,
    redirect: '/horizontal-projects/list',
    name: 'HorizontalProjects',
    meta: { title: '横向课题', icon: 'Document' },
    children: [
      {
        path: 'list',
        name: 'HorizontalProjectList',
        component: () => import('@/views/horizontal-projects/list.vue'),
        meta: { title: '课题列表', icon: 'List' }
      },
      {
        path: 'create',
        name: 'HorizontalProjectCreate',
        component: () => import('@/views/horizontal-projects/form.vue'),
        meta: { title: '添加课题', icon: 'Plus', roles: ['STUDENT'] }
      },
      {
        path: 'edit/:id',
        name: 'HorizontalProjectEdit',
        component: () => import('@/views/horizontal-projects/form.vue'),
        meta: { title: '编辑课题', hidden: true, roles: ['STUDENT'] }
      }
    ]
  },
  {
    path: '/papers',
    component: Layout,
    redirect: '/papers/list',
    name: 'Papers',
    meta: { title: '学术论文', icon: 'Document' },
    children: [
      {
        path: 'list',
        name: 'PaperList',
        component: () => import('@/views/papers/list.vue'),
        meta: { title: '论文列表', icon: 'List' }
      },
      {
        path: 'create',
        name: 'PaperCreate',
        component: () => import('@/views/papers/form.vue'),
        meta: { title: '添加论文', icon: 'Plus', roles: ['STUDENT'] }
      },
      {
        path: 'edit/:id',
        name: 'PaperEdit',
        component: () => import('@/views/papers/form.vue'),
        meta: { title: '编辑论文', hidden: true, roles: ['STUDENT'] }
      }
    ]
  },
  {
    path: '/audit',
    component: Layout,
    redirect: '/audit/pending',
    name: 'Audit',
    meta: { title: '审核管理', icon: 'Check', roles: ['TEACHER', 'ADMIN'] },
    children: [
      {
        path: 'pending',
        name: 'AuditPending',
        component: () => import('@/views/audit/pending.vue'),
        meta: { title: '待审核项目', icon: 'Clock', roles: ['TEACHER', 'ADMIN'] }
      },
      {
        path: 'history',
        name: 'AuditHistory',
        component: () => import('@/views/audit/history.vue'),
        meta: { title: '审核历史', icon: 'Document', roles: ['TEACHER', 'ADMIN'] }
      }
    ]
  },
  {
    path: '/user-management',
    component: Layout,
    redirect: '/user-management/users',
    name: 'UserManagement',
    meta: { title: '用户管理', icon: 'User', roles: ['ADMIN', 'TEACHER'] },
    children: [
      {
        path: 'users',
        name: 'UserList',
        component: () => import('@/views/user-management/users.vue'),
        meta: { title: '用户列表', icon: 'List', roles: ['ADMIN'] }
      },
      {
        path: 'students',
        name: 'StudentManagement',
        component: () => import('@/views/user-management/students.vue'),
        meta: { title: '学生管理', icon: 'User', roles: ['TEACHER'] }
      }
    ]
  },
  {
    path: '/profile',
    component: Layout,
    redirect: '/profile/index',
    children: [
      {
        path: 'index',
        name: 'Profile',
        component: () => import('@/views/profile/index.vue'),
        meta: { title: '个人中心', icon: 'User' }
      }
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: NotFound,
    meta: { title: '404', hidden: true }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404',
    meta: { hidden: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = store.getters.token

  if (to.path === '/login') {
    if (token) {
      next({ path: '/' })
    } else {
      next()
    }
  } else {
    if (token) {
      // 检查是否有用户信息
      const userInfo = store.getters.userInfo
      if (!userInfo || !userInfo.id) {
        try {
          await store.dispatch('user/getUserInfo')
        } catch (error) {
          ElMessage.error('获取用户信息失败')
          store.dispatch('user/logout')
          next('/login')
          return
        }
      }

      // 检查路由权限
      if (to.meta.roles) {
        const userRoles = store.getters.roles
        const hasPermission = to.meta.roles.some(role => userRoles.includes(role))
        if (hasPermission) {
          next()
        } else {
          ElMessage.error('没有权限访问该页面')
          next('/404')
        }
      } else {
        next()
      }
    } else {
      next('/login')
    }
  }
})

export default router
